package com.YxyBackMange.Service.web.impl;

import com.YxyBackMange.Dto.QueryInfo;
import com.YxyBackMange.Entity.Sys.SysReUserRole;
import com.YxyBackMange.Entity.Sys.SysRole;
import com.YxyBackMange.Entity.Sys.SysUser;
import com.YxyBackMange.Mapper.web.WebSysReUserRoleMapper;
import com.YxyBackMange.Mapper.web.WebSysRoleMapper;
import com.YxyBackMange.Mapper.web.WebSysUserMapper;
import com.YxyBackMange.Service.web.WebSysUserService;
import com.YxyBackMange.Util.MD5;
import com.YxyBackMange.Util.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @outhor 路♥克
 * 2017-12-05 18:10
 */
@Service
public class WebSysUserServiceImpl implements WebSysUserService {

    @Autowired
    private WebSysUserMapper webSysUserMapper;
    @Autowired
    private WebSysReUserRoleMapper webSysReUserRoleMapper;
    @Autowired
    private WebSysRoleMapper webSysRoleMapper;
    @Override
    public SysUser insertService(SysUser o) {

        String password= MD5.createMD5(o.getToken());
        String salt= MyUtil.getRandomCharAndNumr(10);
        o.setRegisterTime(new Date());
        if(o.getIdentity()==null){
            o.setIdentity(o.getPhone());
        }
        if(o.getUsername()==null){
            o.setUsername(o.getPhone());
        }
        o.setSalt(salt);
        o.setToken(MD5.createMD5(password+salt));
        try {
            webSysUserMapper.insertSelective(o);
        } catch (Exception e) {
            return null;
        }
        SysRole sysRole = new SysRole();
        sysRole.setIsDefault(1);
        List<SysRole> sysRoleList = webSysRoleMapper.select(sysRole);
        for (SysRole sysRoles : sysRoleList) {
            SysReUserRole sysReUserRole=new SysReUserRole();
            sysReUserRole.setUserId(o.getId());
            sysReUserRole.setRoleId(sysRoles.getId());
            webSysReUserRoleMapper.insertSelective(sysReUserRole);
        }
        return o;
    }

    @Override
    public SysUser updateService(SysUser o) {
        int i = webSysUserMapper.updateByPrimaryKeySelective(o);
        if (i>0){
            return o;
        }
        return null;
    }

    @Override
    public SysUser insert(SysUser o) {
        return null;
    }

    @Override
    public SysUser update(SysUser o) {
        webSysUserMapper.updateByIdentity(o);
        SysUser user = new SysUser();
        user.setIdentity(o.getIdentity());
        return webSysUserMapper.selectOne(user);
    }

    @Override
    public SysUser delete(SysUser o) {
        return null;
    }
}
